package com.xxxx.springsecuritydemo.handle;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final String forwardUrl;

    public MyAuthenticationSuccessHandler(String forwardUrl) {
        this.forwardUrl = forwardUrl;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        // 可以获取用户信息
        System.out.println(user.getUsername());
        System.out.println(user.getPassword()); // 为了安全, 密码显示null
        System.out.println(user.getAuthorities());

        System.out.println(request.getRemoteAddr());
        System.out.println(request.getRequestURI());
        response.sendRedirect(forwardUrl);
    }
}
